<?php

namespace model;

use common\Model;
use common\Check;

class admin_user extends Model
{
	const CACHENAME = "admin_user_";
	const TABLE = 'admin_user';
	protected $DB;
	function __construct()
	{
		$this->DB = parent::db();
	}

	//登录判断用户名和密码
	public function CheckLogin()
	{
		$where['username'] = $_POST['username'];
		$where['password'] = md5($_POST['password']);
		return $this->DB->table(self::TABLE)->where($where)->find();
	}
	//将登录信息写入数据库
	public function loginDbInsert($userId)
	{
		$updateDate = [
			'logintime' => date('Y-m-d H:i:s', time()),
			'loginip' => GetIp(),
		];
		return $this->DB->table(self::TABLE)->where(['id' => $userId])->update($updateDate);
	}

	//查找一条信息
	public function findData($id = null)
	{
		$whereid = $id ?: $_GET['id'];
		$data = GetCxuuCache(self::CACHENAME . $whereid);
		if (empty($data)) {
			$data = $this->DB->table(self::TABLE)->where(['id' => $whereid])->find();
			SetCxuuCache(self::CACHENAME . $whereid, $data); //永久保存
		}
		return $data;
	}

	//获取数据并分页
	public function jsonPageSelect()
	{
		//$where['a.id <>'] = 1;
		$p = intval($_GET['page'] ?? 0) ?: 1;
		$num = intval($_GET['limit'] ?? 0) ?: 10;
		$page = ['num' => $num, 'p' => $p, 'return' => true];
		$field = 'b.id as groupid,b.groupname,a.id,a.gid,a.username,a.nickname,a.logintime,a.loginip,a.status,a.phone,a.photo';
		$join = 'LEFT JOIN admin_group b ON a.gid=b.id';

		return [
			'data' => $this->DB->table(self::TABLE . ' a')->field($field)->join($join)->Page($page)->order('a.id DESC')->select(),
			'page' => $this->DB->getPage()
		];
	}

	//判断用户名是否存在
	private function checkNameData($username)
	{
		if (empty($_POST['id'])) {
			$where['username'] = $username; //新建时比对
		} else {
			//验证用户名是否存在 查询不等当前用户的数据进行比对
			//$where = "id <> ".$_POST['id']." AND username = '{$username}'";
			$where = [
				'id <>' => $_POST['id'],
				'username' => $username,
			];
		}
		return $this->DB->table(self::TABLE)->where($where)->find();
	}
	//添加数据
	public function insertData()
	{
		$username = VarFilter($_POST['username']);
		//验证用户组名是否存在
		if (!empty($this->checkNameData($username))) {
			return ['status' => 0, 'msg' => '用户名已经存在！'];
		}

		$data = [
			'gid' => $_POST['gid'],
			'username' => $username,
			'nickname' => VarFilter($_POST['nickname']),
			'phone' => intval($_POST['phone']),
			'photo' => VarFilter($_POST['photo']),
			'password' => md5(trim($_POST['password'])),
			'status' => $_POST['status'],
		];
		//验证数据
		$check = Check::rule(
			[check::must($data['username']), '用户名不能为空'],
			[check::userName($data['username'], 4, 20), '用户名为4-20个字符的英文加字母，请检查'],
			[check::isChinese($data['nickname']), '真实姓名必须为中文，请检查'],
			[check::isImg($data['photo']), '请输入有效头像地址，请检查'],
			[check::mobile($data['phone']), '请输入有效手机号码，请检查']
		);
		if ($check !== true) {
			return ['status' => 0, 'msg' => $check];
		} else {
			if (0 < $this->DB->table(self::TABLE)->insert($data)) {
				SqlLog("添加用户：" . $_POST['username']);
				return ['status' => 1, 'msg' => '添加成功', 'cid' => $_POST['cid']];
			} else {
				return ['status' => 0, 'msg' => '写入数据库错误！'];
			}
		}
	}
	//关联更新数据
	public function updateData()
	{
		$userid = $_POST['id'];
		if ($userid == 1) return ['status' => 0, 'msg' => '创始帐户不能在这里修改！'];	//创始帐户不能在这里修改！
		$username = VarFilter($_POST['username']);
		if (!empty($this->checkNameData($username))) return ['status' => 0, 'msg' => '用户名已经存在！']; //验证用户组名是否存在
		$data = [
			'gid' => $_POST['gid'],
			'username' => $username,
			'nickname' => VarFilter($_POST['nickname']),
			'phone' => VarFilter($_POST['phone']),
			'photo' => VarFilter($_POST['photo']),
			'status' => $_POST['status'],
		];
		if (!empty($_POST['password'])) {
			$data = array_merge($data, ['password' => md5(trim($_POST['password']))]);
		}
		$check = Check::rule(
			[check::must($data['username']), '用户名不能为空'],
			[check::userName($data['username'], 4, 20), '用户名为4-20个字符的英文加字母，请检查'],
			[check::isChinese($data['nickname']), '真实姓名必须为中文且不能空，请检查'],
			[check::isImg($data['photo']), '请输入有效头像地址，请检查'],
			[check::mobile($data['phone']), '请输入有效手机号码，请检查'],
		);
		if ($check !== true) return ['status' => 0, 'msg' => $check];
		if (0 < $this->DB->table(self::TABLE)->Where(['id' => $userid])->Update($data)) {
			SqlLog("编辑用户：" . $username);
			DelCxuuCache(self::CACHENAME . $userid); //删除对应缓存
			return ['status' => 1, 'msg' => '修改成功'];
		} else {
			return ['status' => 0, 'msg' => '数据没有变化'];
		}
	}

	//用户自行修改密码
	public function passwordEdit()
	{
		$userid = $_POST['id'];
		$data = [
			'nickname' => VarFilter($_POST['nickname']),
			'phone' => VarFilter($_POST['phone']),
			'photo' => VarFilter($_POST['photo']),
		];
		if (!empty($_POST['password'])) {
			$data = array_merge($data, ['password' => md5(trim($_POST['password']))]);
		}
		$check = Check::rule(
			[check::isChinese($data['nickname']), '昵称必须为中文且不能空，请检查'],
			[check::isImg($data['photo']), '请输入有效头像地址，请检查'],
			[check::mobile($data['phone']), '请输入有效手机号码，请检查'],
		);
		if ($check !== true) return ['status' => 0, 'msg' => $check];
		if (0 < $this->DB->table(self::TABLE)->Where(['id' => $userid])->Update($data)) {
			SqlLog("用户自行修改昵称和密码 ID：" . $userid);
			DelCxuuCache(self::CACHENAME .  $userid); //删除对应缓存
			return ['status' => 1, 'msg' => '修改成功'];
		} else {
			return ['status' => 0, 'msg' => '数据没有变化'];
		}
	}

	public function switchStatus()
	{
		$userid = $_POST['id'];
		if ($userid == 1) return ['status' => 0, 'msg' => '创始帐户不能禁用！'];
		SqlLog("切换用户禁用状态 ID:" . $userid);
		if (0 < $this->DB->table(self::TABLE)->where(['id' => $userid])->Update(['status' => $_POST['status']])) {
			DelCxuuCache(self::CACHENAME .  $userid); //删除对应缓存
			return ['status' => 1, 'msg' => '设置成功-已经登录用户将被强制离线！'];
		} else
			return ['status' => 0, 'msg' => '设置失败！'];
	}


	//删除一条数据
	public function deleteOneData()
	{
		$userid = $_POST['id'];
		if ($userid == 1) return ['status' => 0, 'msg' => '创始帐户不能删除！'];
		if ($this->DB->table(self::TABLE)->where(['id' => $userid])->Delete()) {
			SqlLog("删除用户：" . $userid);
			DelCxuuCache(self::CACHENAME . $userid); //删除对应缓存
			return ['status' => 1, 'msg' => '删除成功-已经登录用户将被强制离线！'];
		} else
			return ['status' => 0, 'msg' => '删除失败！'];
	}
}
